/**
 * @description  手动入池
 * @author shenhong
 */
import React, { PropTypes, PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Divider, Select, message, Row, Col, Upload, Table, Input } from 'antd';
import moment from 'moment';
import queryString from 'query-string';
import { FirstHeaderC, DATA_ENTRY, TableC, SecondHeaderC, AdvancedSearch } from '../../../comps';
import { FormItemLayout } from '../../../comps/form/formPub';
import styles from './index.less';
import ManualTable from '../typeTable/manualTable';
import { exportFile } from '../../../utils/commonFunc';

const { TextArea } = Input;
const FormItem = Form.Item;
@Form.create()
class MenualInPool extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      businessKey: '',
      type: '',
      fileList: [],
    };
  }

  componentDidMount() {
    const { dispatch, businessKey } = this.props;
    if (businessKey !== undefined) {
      this.queryDataById(businessKey);
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { businessKey, dispatch, timeStamp } = nextProps;
    if (timeStamp !== this.props.timeStamp || businessKey !== this.props.businessKey) {
      if (businessKey !== undefined) {
        this.queryDataById(businessKey);
      }
    }
  }

  // 获取审批详情数据
  queryDataById = (businessKey) => {
    this.props.dispatch({
      type: 'agencyTaskM/getPoolData',
      payload: {
        type: 'pool',
        id: businessKey,
      },
      callback: (res) => {
        if (res) {
          const data = res.dataSource;
          const formData = data.flowEditVo;
          if (formData.files) {
            this.changeFileList(formData.files);
          }
        } else {
          this.setState({
            fileList: [],
          });
        }
      },
    });
  };

  // 将filelist 转换成upload组件接收的样子
  changeFileList = (data) => {
    const fileList = [];
    data.map((item) => {
      const obj = {
        uid: item.value,
        name: item.title,
        status: 'done',
        fileId: item.value,
        url: '#',
      };
      fileList.push(obj);
    });
    this.setState({
      fileList,
    });
  };

  ajaxRequest(method, url, type) {
    return new Promise((resolve, reject) => {
      const req = new XMLHttpRequest();
      req.open(method, url, true);
      req.setRequestHeader('Content-Type', 'application/json');
      req.setRequestHeader('hToken', localStorage.getItem('antd-pro-token'));

      req.responseType = type;
      req.onreadystatechange = () => {
        // readyState == 4说明请求已完成
        if (req.readyState === 4) {
          const data = req.response;
          // # 获取请求头Content-Type的值，用来判断是否是文件流下载
          const type = req.getResponseHeader('Content-Type');

          if (req.status === 200 || req.status === 304) {
            // # application/json就是指“无类型”，一般的字节流用于数据传输，非文件下载
            if (type !== 'multipart/form-data;charset=UTF-8') {
              resolve(undefined);
            } else {
              resolve(data);
            }
          } else {
            reject(undefined);
          }
        }
      };
      // 发送数据
      req.send();
    });
  }

  render() {
    const {
      agencyTaskM: { poolData },
    } = this.props;
    const data = poolData.dataSource;
    const formData = data.flowEditVo;
    const test = data.inPoolWay == 'manual' ? '手动入池审批' : '自动入池审批';
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'flowName',
          title: '流程名称',
          type: DATA_ENTRY.INPUT,
          disabled: true,
          initialValue: formData.flowName,
        },
        {
          dataIndex: 'securityName',
          title: '券池名称',
          type: DATA_ENTRY.INPUT,
          disabled: true,
          initialValue: formData.securityId,
        },

        {
          dataIndex: 'securityType',
          title: '券池类型',
          type: DATA_ENTRY.INPUT,
          disabled: true,
          initialValue: formData.securityType,
        },
        {
          dataIndex: 'direction',
          title: '操作方向',
          type: DATA_ENTRY.INPUT,
          disabled: true,
          initialValue: formData.direction,
        },
        {
          dataIndex: 'flowapplicant',
          title: '流程申请人',
          type: DATA_ENTRY.INPUT,
          disabled: true,
          initialValue: formData.applicant,
        },
      ],
      onQuery: false,
      onClear: false,
    };

    return (
      <div style={{ marginBottom: '10px' }}>
        <div style={{ marginBottom: '10px' }}>
          <FirstHeaderC title={`${test}`} />
        </div>
        <div style={{ marginBottom: '10px' }}>
          <SecondHeaderC title='通用要素' />
        </div>

        <div style={{ marginBottom: '10px' }} className={styles.tongyong}>
          <div className={styles.advanceSearch}>
            <AdvancedSearch {...searchProps} allowClear={false} allowQuery={false} />
          </div>
          {data.inPoolWay == 'manual' ? (
            <>
              <div className={'pool-remark'}>
                <FormItem label={'备注'} {...FormItemLayout}>
                  <TextArea style={{ width: '100%', height: '60px' }} value={formData.remark} placeholder='' disabled={true} />
                </FormItem>
              </div>
              <div className={'pool-remark'}>
                <FormItem label={'附件'} {...FormItemLayout}>
                  <Upload
                    fileList={this.state.fileList}
                    showUploadList={{ showRemoveIcon: false }}
                    disabled={true}
                    onPreview={(file) => {
                      // 进行文件下载

                      if (file.status == 'error') return;
                      exportFile(`gateway/file/maat-admin/file/download`, { uniquekey: file.fileId });
                    }}
                  >
                    {this.state.fileList.length ? undefined : '无数据'}
                  </Upload>
                </FormItem>
              </div>
            </>
          ) : null}
        </div>
        <div style={{ marginTop: '20px' }}>{<ManualTable poolData={poolData} />}</div>
      </div>
    );
  }
}
export default connect(({ agencyTaskM }) => ({
  agencyTaskM,
}))(MenualInPool);
